package cn.mesmile.flow.config.listen;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.BaseEntityEventListener;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author zb
 * @date 2020/12/25 11:48
 * @Description
 */
@Slf4j
@Component
public class GlobalTaskCreateListener extends AbstractFlowableEngineEventListener {

    /**
     * {@link BaseEntityEventListener}
     *
     * org.flowable.engine.delegate.event.BaseEntityEventListener: 事件监听器基类，
     * 可用来监听实体（entity）相关事件，特定或所有实体的事件都可以。它隐藏了类型检测，
     * 提供了4个需要覆盖的方法：onCreate(..), onUpdate(..)与onDelete(..)在实体创建、更新及删除时调用；
     * 对所有其他实体相关事件，onEntityEvent(..)会被调用。
     *
     */

    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        log.info(">>>>>>>>>>>>>>>> 进入到任务创建监听器,时间；{}", DateUtil.now());
        try {
            if (event instanceof FlowableEntityEventImpl) {
                FlowableEntityEventImpl eventImpl = (FlowableEntityEventImpl) event;
                //得到任务实例
                TaskEntity entity = (TaskEntity) eventImpl.getEntity();
                System.out.println("entity.getProcessInstanceId() = " + entity.getProcessInstanceId());
                System.out.println("entity.getTaskDefinitionKey() = " + entity.getTaskDefinitionKey());
                System.out.println("entity.getTaskDefinitionId() = " + entity.getTaskDefinitionId());

                //1.同步流程扩展
                //2.流程外部推送
                //3.获取当前审批人  通过  entity
                String assignee = entity.getAssignee();
                System.out.println("assignee = " + assignee);

                Set<IdentityLink> candidates = entity.getCandidates();
                for (IdentityLink candidate : candidates) {
                    String userId = candidate.getUserId();
                    System.out.println("userId = " + userId);
                }
                //4.同步OA

            }
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>> 设置审批人监听器异常", e);
        }
    }


}
